package service

import (
	"fmt"
	"io"
	"net/http"
	"noip_updator/common"
	"strings"

	"github.com/spf13/viper"
)

type DnsUpdator struct {
	protocol  string
	user, pwd string
	api       string
	host      string
}

func NewDnsUpdator() *DnsUpdator {
	common.Logger.Info("update service init...")
	return newDnsUpdator(
		viper.GetBool("ddns.ssl"),
		viper.GetString("ddns.user"),
		viper.GetString("ddns.pwd"),
		viper.GetString("ddns.api"),
		viper.GetString("ddns.myhostname"),
	)
}

func newDnsUpdator(ssl bool, user, pwd, api, host string) *DnsUpdator {
	protocol := "http"
	if ssl {
		protocol = "https"
	}
	return &DnsUpdator{
		protocol: protocol,
		user:     user,
		pwd:      pwd,
		api:      api,
		host:     host,
	}
}

func (server *DnsUpdator) Update(ips []string) (bool, []byte) {
	uri := fmt.Sprintf(
		"%s://%s?hostname=%s&myip=%s",
		server.protocol, server.api, server.host,
		strings.Join(ips, ","),
	)
	client := http.Client{}
	req, _ := http.NewRequest("GET", uri, nil)
	req.SetBasicAuth(server.user, server.pwd)
	resp, err := client.Do(req)
	if err != nil {
		common.Logger.Errorf("client.Do err:%v", err)
		return false, []byte{}
	}
	defer resp.Body.Close()
	common.Logger.Info("update request sent")
	var success bool
	if resp.StatusCode == 200 {
		success = true
	} else {
		success = false
	}
	body, _ := io.ReadAll(resp.Body)
	return success, body
}
